package com.itheima.tlias84.aspect;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.dao.entity.Emp;
import com.itheima.tlias84.dao.entity.Log;
import com.itheima.tlias84.dao.mapper.EmpMapper;
import com.itheima.tlias84.dao.mapper.LogMapper;
import com.itheima.tlias84.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class LogAspect {

    HttpServletRequest req;

    LogMapper logMapper;

    EmpMapper empMapper;

    @Transactional
    @Around("@annotation(com.itheima.tlias84.annotation.Log)")
    public Object insertLog(ProceedingJoinPoint point) {

        long start = System.currentTimeMillis();

        try {
            String token = req.getHeader("token");
            JSONObject jsonObject = JwtUtil.verifyToken(token);
            Emp emp = empMapper.selectByUsername(jsonObject.getString("username"));

            Object proceed = point.proceed();
            long end = System.currentTimeMillis() - start;
            log.info("操作{}方法插入日志", point.getSignature().getName());

            Log build = Log.builder()
                    .operateEmpId(emp.getId())
                    .operateTime(LocalDateTime.now())
                    .className(point.getTarget().getClass().getSimpleName())
                    .methodName(point.getSignature().getName())
                    .methodParams(Arrays.toString(point.getArgs()))
                    .returnValue(proceed.toString())
                    .costTime((int) end)
                    .operateEmpName(emp.getName()).build();

            logMapper.insertLog(build);

            return proceed;
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

}
